# -*- coding: utf-8 -*-
###############################################################################
# file    : middle_session_check.py
# author  : wangyubin
# date    : Sat Apr  5 10:40:31 2014
#
# brief   : middle ware for check if login or not
# history : init
###############################################################################

from uliweb import Middleware
from db_app.model_define import T_USER

class middle_session_check(Middleware):
    """ 每次请求开始时检查用户是否登录
    """
    ORDER = 100
    # json接口不用进行session check
    JSON_INTERFACES = [
        '/login',
        '/auth/register',
    ]


    def process_request(self, request):
        """ 不是 login 页面, 并且也没有login的话
            迁移到 /login 页面
        """

        for url in self.JSON_INTERFACES:
            if request.path == url:
                return

        from uliweb import settings, redirect
        # print request.path
        # print request.session.has_key(settings.SESSION.SESSION_ID)
        if not request.session.has_key(settings.SESSION.SESSION_ID):
            return redirect('/login')

        # 获取用户信息
        user_id = request.session[settings.SESSION.SESSION_ID]["userid"]
        user = T_USER.get(user_id)
        request.user = user

